package JDBC工具包;

import 数据库操作.Find_;

import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;

/**
 * @作者:侯国威
 * @时间: 2020/4/15/22:19
 * @邮箱:1045077189@qq.com
 */
public class select {
    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {

        Connection connection = null;

        PreparedStatement preparedStatement = null;

        ResultSet resultSet = null;
        try {
            connection = JDBCPackage.getconnection();

            preparedStatement = connection.prepareStatement(sql);

            //处理结果集一行数据中的每一个列
            for (int i = 0; i < args.length; i++) {

                //获取列值
                preparedStatement.setObject(i + 1, args[i]);
            }
            //结果集
            resultSet = preparedStatement.executeQuery();

            //ResultSetMetaData确定要使用的列名。列名是根据a确定的使用ResultSetMetaData查找
            //获取结果集的元数据

            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();

            int ColumnCount = resultSetMetaData.getColumnCount();//获取每一列
            //通过ResultSetMetaData获取结果集中的数据

            if (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < ColumnCount; i++) {
                    Object columvalue = resultSet.getObject(i + 1);//列值

                    //获取每个列的列名
                    String columnName = resultSetMetaData.getColumnName(i + 1);

                    //给 find_对象指定的某个对象，赋值为columvalue

                    Field field = clazz.getDeclaredField(columnName);

                    field.setAccessible(true);

                    field.set(t, columvalue);
                }
                System.out.println(t);
            }


        } catch (IOException | IllegalAccessException | IllegalArgumentException | NoSuchFieldException | ClassNotFoundException | SQLException | SecurityException | InstantiationException e) {

            e.printStackTrace();

        } finally {

            JDBCPackage.closeResourceInsert(connection, preparedStatement, resultSet);

        }

        return null;
    }
}
